package com.liu.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liu.model.User;
import com.liu.model.UserDao;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.setContentType("text/html; charset=utf8");
        System.out.println(1);
        if (username == null || "".equals(username) || password == null || "".equals(password)) {
            resp.getWriter().write("用户名或密码不能为空！");
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.register(username, password);
        System.out.println(2);
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        resp.sendRedirect("blog_list.html");
    }
}